package com.ruoyi.web.controller.ora;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.dict.DevicePermission;
import com.ruoyi.common.enums.dict.DeviceUserStatus;
import com.ruoyi.common.enums.dict.UserMessageType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ora.domain.DeviceUser;
import com.ruoyi.ora.domain.UserMessage;
import com.ruoyi.ora.service.ICommonService;
import com.ruoyi.ora.service.IDeviceUserService;
import com.ruoyi.ora.service.IUserMessageService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.List;

/**
 * 设备用户关系Controller
 * 
 * @author liuwp
 * @date 2024-11-14
 */
@RestController
@RequestMapping("/ora/device_user")
public class DeviceUserController extends BaseController
{
    @Autowired
    private IDeviceUserService deviceUserService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IUserMessageService userMessageService;

    @Autowired
    private ICommonService commonService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 查询设备用户关系列表
     */
    @PreAuthorize("@ss.hasPermi('ora:device_user:list')")
    @GetMapping("/list")
    public TableDataInfo list(DeviceUser deviceUser)
    {
        startPage();
        List<DeviceUser> list = deviceUserService.selectDeviceUserList(deviceUser);
        return getDataTable(list);
    }

    /**
     * 导出设备用户关系列表
     */
    @PreAuthorize("@ss.hasPermi('ora:device_user:export')")
    @Log(title = "设备用户关系", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DeviceUser deviceUser)
    {
        List<DeviceUser> list = deviceUserService.selectDeviceUserList(deviceUser);
        ExcelUtil<DeviceUser> util = new ExcelUtil<DeviceUser>(DeviceUser.class);
        util.exportExcel(response, list, "设备用户关系数据");
    }

    /**
     * 获取设备用户关系详细信息
     */
    @PreAuthorize("@ss.hasPermi('ora:device_user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(deviceUserService.selectDeviceUserById(id));
    }

    /**
     * 新增设备用户关系
     */
    @PreAuthorize("@ss.hasPermi('ora:device_user:add')")
    @Log(title = "设备用户关系", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DeviceUser deviceUser)
    {
        return toAjax(deviceUserService.insertDeviceUser(deviceUser));
    }

    /**
     * 修改设备用户关系
     */
    @PreAuthorize("@ss.hasPermi('ora:device_user:edit')")
    @Log(title = "设备用户关系", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DeviceUser deviceUser)
    {
        return toAjax(deviceUserService.updateDeviceUser(deviceUser));
    }

    /**
     * 删除设备用户关系
     */
    @PreAuthorize("@ss.hasPermi('ora:device_user:remove')")
    @Log(title = "设备用户关系", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(deviceUserService.deleteDeviceUserByIds(ids));
    }


    @GetMapping("/circle")
    public AjaxResult circle(DeviceUser deviceUser)
    {
//        Long familyId = SecurityUtils.getLoginUser().getUser().getFamilyId();  && familyId != null
        if (deviceUser.getDeviceId() != null) {
//            deviceUser.setFamilyId(familyId);
            deviceUser.setStatus(DeviceUserStatus.BIND.getValue());
            List<DeviceUser> list = deviceUserService.selectDeviceUserList(deviceUser);
            for (DeviceUser user : list) {
                user.setSysUser(sysUserService.selectUserById(user.getUserId()));
            }
            return AjaxResult.success(list);
        }else {
            return AjaxResult.error(MessageUtils.message("ora.common.required"));
        }
    }

    @DeleteMapping("/circle/{id}")
    public AjaxResult circleDelete(@PathVariable Long id)
    {
        DeviceUser deviceUser = deviceUserService.selectDeviceUserById(id);
        if (deviceUser != null){
            deviceUser.setStatus(DeviceUserStatus.DELETE.getValue());
            return toAjax(deviceUserService.updateDeviceUser(deviceUser));
//            if (deviceUser.getUserId().longValue() != SecurityUtils.getUserId().longValue()) {
//                deviceUser.setStatus(DeviceUserStatus.DELETE.getValue());
//                return toAjax(deviceUserService.updateDeviceUser(deviceUser));
//            }else {
//                return AjaxResult.error(MessageUtils.message("ora.device.opeself"));
//            }
        }
        return AjaxResult.error();
    }

    @PostMapping("/circle/permission")
    public AjaxResult permission(DeviceUser deviceUser)
    {
        DeviceUser deviceUser1 = deviceUserService.selectDeviceUserById(deviceUser.getId());
        if (deviceUser1 != null){
            deviceUser1.setDevicePermission(deviceUser.getDevicePermission());
            return toAjax(deviceUserService.updateDeviceUser(deviceUser1));
//            if (deviceUser1.getUserId().longValue() != SecurityUtils.getUserId().longValue()) {
//                deviceUser1.setDevicePermission(deviceUser.getDevicePermission());
//                return toAjax(deviceUserService.updateDeviceUser(deviceUser1));
//            }else {
//                return AjaxResult.error(MessageUtils.message("ora.device.opeself"));
//            }
        }
        return AjaxResult.error();
    }

    @PostMapping("/circle/scanin")
    public AjaxResult scanin(DeviceUser deviceUser)
    {
        if (deviceUser.getDeviceId() != null && deviceUser.getInviteId() != null) {
            DeviceUser inviteUser = deviceUserService.selectOneDeviceUser(Builder.of(DeviceUser::new)
                    .with(DeviceUser::setDeviceId, deviceUser.getDeviceId())
                    .with(DeviceUser::setUserId, deviceUser.getInviteId())
                    .with(DeviceUser::setStatus, DeviceUserStatus.BIND.getValue())
                    .build());
            if (inviteUser != null) {
                // 这个扫码入圈接口其实和绑定逻辑是一样的 ，但这里也单独写了
                DeviceUser build = Builder.of(DeviceUser::new)
                        .with(DeviceUser::setDeviceId, deviceUser.getDeviceId())
                        .with(DeviceUser::setUserId, SecurityUtils.getUserId())
                        .with(DeviceUser::setStatus, DeviceUserStatus.BIND.getValue())
                        .build();
                DeviceUser deviceUser1 = deviceUserService.selectOneDeviceUser(build);

                if (deviceUser1 != null){
                    return AjaxResult.success(deviceUser1);
                }else {
                    build.setDevicePermission(DevicePermission.MEMBER.getValue());
                    build.setDeviceRelationId(inviteUser.getDeviceRelationId());
                    build.setOperId(inviteUser.getUserId());
                    build.setInviteId(inviteUser.getUserId());

                    int i = deviceUserService.insertDeviceUser(build);

                    userMessageService.insertUserMessage(Builder.of(UserMessage::new)
                            .with(UserMessage::setUserId, build.getUserId())
                            .with(UserMessage::setMsgType, UserMessageType.MEM_JOIN.getValue())
                            .with(UserMessage::setAssetsId1, build.getId().toString())
                            .with(UserMessage::setMsgTitle, "欢迎【"+SecurityUtils.getLoginUser().getUser().getUserName()+"】的加入").build());

                    return toAjax(i);
                }
            }else {
                return AjaxResult.error();
            }
        }else {
            return AjaxResult.error(MessageUtils.message("ora.common.required"));
        }
    }


    @PostMapping("/circle/invite")
    public AjaxResult invite(DeviceUser deviceUser){
        if (deviceUser.getDeviceId() != null) {
            DeviceUser inviteUser = deviceUserService.selectOneDeviceUser(Builder.of(DeviceUser::new)
                    .with(DeviceUser::setDeviceId, deviceUser.getDeviceId())
                    .with(DeviceUser::setUserId, SecurityUtils.getUserId())
                    .with(DeviceUser::setStatus, DeviceUserStatus.BIND.getValue())
                    .build());
            if (inviteUser != null) {
                DeviceUser build = Builder.of(DeviceUser::new)
                        .with(DeviceUser::setDeviceId, deviceUser.getDeviceId())
                        .with(DeviceUser::setUserName, deviceUser.getUserName())
                        .with(DeviceUser::setStatus, DeviceUserStatus.BINDING.getValue())
                        .build();
                DeviceUser deviceUser1 = deviceUserService.selectOneDeviceUser(build);

                // TODO 发送邀请连接
                if (deviceUser1 == null){
                    deviceUser1 = build;
                    deviceUser1.setDevicePermission(DevicePermission.MEMBER.getValue());
                    deviceUser1.setDeviceRelationId(inviteUser.getDeviceRelationId());
                    deviceUser1.setOperId(inviteUser.getUserId());
                    deviceUser1.setInviteId(inviteUser.getUserId());
                    return toAjax(deviceUserService.insertDeviceUser(deviceUser1));
                }

                String agreeInvitation = configService.selectConfigByKey("ora_agree_invitation");

                String content = "用户【"+SecurityUtils.getLoginUser().getUser().getNickName()+"】邀请您进入家庭圈，使用此号码登录OraMemoApp进入家庭圈！点击链接同意邀请："+agreeInvitation + "?inviteId="+deviceUser1.getId();

                boolean result = false;
                // 发送邀请消息
                if (deviceUser.getUserName().contains("@")){
                    result = commonService.sendEmail(deviceUser.getUserName().split(","), "邀请家庭圈申请", content, null);
                }else {
                    result = commonService.sendSms(deviceUser.getUserName(), content, "zh");
                }

                return AjaxResult.success(deviceUser1);
            }else {
                return AjaxResult.error();
            }
        }else {
            return AjaxResult.error(MessageUtils.message("ora.common.required"));
        }
    }

    // 同意入圈
//    @GetMapping("/circle/agree")
//    public AjaxResult agree(Long inviteId){
//        if (inviteId != null){
//            DeviceUser deviceUser = deviceUserService.selectDeviceUserById(inviteId);
//            if (deviceUser != null){
//                deviceUser.setStatus(DeviceUserStatus.BIND.getValue());
//                int result = deviceUserService.updateDeviceUser(deviceUser);
//                // http://oramemo.szcclg.com/app-release.apk
//                return AjaxResult.success(result);
//            }
//        }
//        return AjaxResult.error();
//    }


    @GetMapping("/circle/agree")
    public ResponseEntity<Resource> agree(@RequestParam Long inviteId) throws IOException {
        if (inviteId == null) {
            return ResponseEntity.badRequest().build();
        }

        DeviceUser deviceUser = deviceUserService.selectDeviceUserById(inviteId);
        if (deviceUser == null) {
            return ResponseEntity.notFound().build();
        }

        deviceUser.setStatus(DeviceUserStatus.BIND.getValue());
        int result = deviceUserService.updateDeviceUser(deviceUser);
        if (result <= 0) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }


//        userMessageService.insertUserMessage(Builder.of(UserMessage::new)
//                .with(UserMessage::setUserId, build.getUserId())   // TODO 这个时候还没有用户id呀。。 咋办呢
//                .with(UserMessage::setMsgType, UserMessageType.MEM_JOIN.getValue())
//                .with(UserMessage::setAssetsId1, inviteId.toString())
//                .with(UserMessage::setMsgTitle, "欢迎【"+SecurityUtils.getLoginUser().getUser().getUserName()+"】的加入").build());

//        http://oramemo.szcclg.com/appdownload

//        // 本地文件路径
//        String filePath = "/home/work/ora_memo/html/app-release.apk";
//        File file = new File(filePath);
//
//        if (!file.exists()) {
//            return ResponseEntity.notFound().build();
//        }
//
//        // 使用 FileSystemResource 读取本地文件
//        Resource resource = new FileSystemResource(file);
//
//        // 设置 HTTP 响应头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//        headers.setContentLength(file.length());
//        headers.setContentDispositionFormData("attachment", "app-release.apk");
//        headers.setCacheControl("no-cache, no-store, must-revalidate");
//        headers.setPragma("no-cache");
//        headers.setExpires(0);
//
//        return ResponseEntity.ok()
//                .headers(headers)
//                .body(resource);

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(URI.create("http://oramemo.szcclg.com/appdownload"));
        return new ResponseEntity<>(headers, HttpStatus.FOUND);
    }

}
